package com.zyl.timer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.zyl.bean.Notes;
import com.zyl.util.FileUtil;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.view.WindowManager;
import android.widget.Toast;

public class TimerService extends Service {

	@Override
	public IBinder onBind(Intent intent) {

		return null;

	}

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public void onDestroy() {

	}

	@Override
	public void onStart(Intent intent, int startid) {
		log();
	}

	
	public void log() {
		String message = "";
		message = Notes.log();
		Date d = new Date(System.currentTimeMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		String time = sdf.format(d);
		
		if (!message.equals("")) {

			vibrator();

			final String str = time + " " + message;

			// 启动alertDialog源码:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(message)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
//									try {
//									//	FileUtil.write(str + "  √");
//									} catch (IOException e) {
//
//									}
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									try {
										FileUtil.write(str + "  x");
									} catch (IOException e) {

									}
								}
							});
			AlertDialog ad = builder.create(); //
			ad.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
			// 系统中关机对话框就是这个属性
			ad.getWindow()
					.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			ad.setCanceledOnTouchOutside(false);
			// 点击外面区域不会让dialog消失
			ad.show();

		}
	}



	public void vibrator() {
		Intent i = new Intent(this, TimerVibrator.class);
		PendingIntent pi = PendingIntent.getBroadcast(
				this.getApplicationContext(), 0, i, 0);
		AlarmManager am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, pi);

	}

}
